'use strict';

const Controller = require('egg').Controller;

class CityController extends Controller {
  /**
   * 获取城市列表（支持分页、搜索、排序、标签筛选）
   * GET /api/cities
   * @query {number} page - 页码（默认1）
   * @query {number} pageSize - 每页数量（默认10）
   * @query {string} keyword - 搜索关键词
   * @query {string} tag - 标签筛选
   * @query {string} sortBy - 排序字段（默认created_at）
   * @query {string} sortOrder - 排序方式 asc/desc（默认desc）
   */
  async index() {
    const { ctx, service } = this;
    const { page = 1, pageSize = 10, keyword, tag, sortBy = 'created_at', sortOrder = 'desc' } = ctx.query;

    try {
      const result = await service.city.getList({
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        keyword,
        tag,
        sortBy,
        sortOrder,
      });

      ctx.body = {
        success: true,
        data: result.list,
        pagination: {
          page: result.page,
          pageSize: result.pageSize,
          total: result.total,
          totalPages: result.totalPages,
        },
      };
    } catch (error) {
      ctx.logger.error('获取城市列表失败:', error);
      ctx.status = 500;
      ctx.body = { success: false, message: '获取城市列表失败: ' + error.message };
    }
  }

  /**
   * 获取城市详情
   * GET /api/cities/:id
   */
  async show() {
    const { ctx, service } = this;
    const id = parseInt(ctx.params.id);

    if (Number.isNaN(id)) {
      ctx.status = 400;
      ctx.body = { success: false, message: '无效的ID' };
      return;
    }

    try {
      const data = await service.city.getById(id);
      if (!data) {
        ctx.status = 404;
        ctx.body = { success: false, message: '城市不存在' };
        return;
      }
      ctx.body = { success: true, data };
    } catch (error) {
      ctx.logger.error('获取城市详情失败:', error);
      ctx.status = 500;
      ctx.body = { success: false, message: '获取城市详情失败: ' + error.message };
    }
  }

  /**
   * 创建城市
   * POST /api/cities
   */
  async create() {
    const { ctx, service } = this;
    const payload = ctx.request.body || {};

    // 参数验证
    if (!payload.name) {
      ctx.status = 400;
      ctx.body = { success: false, message: '城市名称不能为空' };
      return;
    }

    try {
      const created = await service.city.create(payload);
      ctx.body = {
        success: true,
        data: created,
        message: '创建成功',
      };
    } catch (error) {
      ctx.logger.error('创建城市失败:', error);
      ctx.status = 500;
      ctx.body = { success: false, message: '创建城市失败: ' + error.message };
    }
  }

  /**
   * 更新城市
   * PUT /api/cities/:id
   */
  async update() {
    const { ctx, service } = this;
    const id = parseInt(ctx.params.id);
    const payload = ctx.request.body || {};

    if (Number.isNaN(id)) {
      ctx.status = 400;
      ctx.body = { success: false, message: '无效的ID' };
      return;
    }

    try {
      const updated = await service.city.update(id, payload);
      if (!updated) {
        ctx.status = 404;
        ctx.body = { success: false, message: '更新失败，城市不存在' };
        return;
      }
      ctx.body = {
        success: true,
        data: updated,
        message: '更新成功',
      };
    } catch (error) {
      ctx.logger.error('更新城市失败:', error);
      ctx.status = 500;
      ctx.body = { success: false, message: '更新城市失败: ' + error.message };
    }
  }

  /**
   * 删除城市
   * DELETE /api/cities/:id
   */
  async destroy() {
    const { ctx, service } = this;
    const id = parseInt(ctx.params.id);

    if (Number.isNaN(id)) {
      ctx.status = 400;
      ctx.body = { success: false, message: '无效的ID' };
      return;
    }

    try {
      const ok = await service.city.remove(id);
      if (!ok) {
        ctx.status = 404;
        ctx.body = { success: false, message: '删除失败，城市不存在' };
        return;
      }
      ctx.body = { success: true, message: '删除成功' };
    } catch (error) {
      ctx.logger.error('删除城市失败:', error);
      ctx.status = 500;
      ctx.body = { success: false, message: '删除城市失败: ' + error.message };
    }
  }

  /**
   * 批量删除城市
   * POST /api/cities/batch-delete
   */
  async batchDelete() {
    const { ctx, service } = this;
    const { ids } = ctx.request.body || {};

    if (!Array.isArray(ids) || ids.length === 0) {
      ctx.status = 400;
      ctx.body = { success: false, message: '请提供要删除的城市ID数组' };
      return;
    }

    try {
      const count = await service.city.batchRemove(ids);
      ctx.body = {
        success: true,
        message: `成功删除 ${count} 个城市`,
        data: { count },
      };
    } catch (error) {
      ctx.logger.error('批量删除城市失败:', error);
      ctx.status = 500;
      ctx.body = { success: false, message: '批量删除失败: ' + error.message };
    }
  }

  /**
   * 推荐城市（推荐数+1）
   * POST /api/cities/:id/recommend
   */
  async recommend() {
    const { ctx, service } = this;
    const id = parseInt(ctx.params.id);

    if (Number.isNaN(id)) {
      ctx.status = 400;
      ctx.body = { success: false, message: '无效的ID' };
      return;
    }

    try {
      const result = await service.city.incrementRecommendations(id);
      if (result.success) {
        ctx.body = {
          success: true,
          data: result.data,
          message: '推荐成功'
        };
      } else {
        ctx.status = 404;
        ctx.body = { success: false, message: result.message || '推荐失败' };
      }
    } catch (error) {
      ctx.logger.error('推荐城市失败:', error);
      ctx.status = 500;
      ctx.body = { success: false, message: '推荐失败: ' + error.message };
    }
  }
}

module.exports = CityController;